package com.appspot.pro_log.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.net.*;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.pro_log.client.GreetingService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService
{
	private static final Logger	log		= Logger.getLogger(GreetingServiceImpl.class.getName());
	
	static int							counter	= 0;
	
	public GreetingServiceImpl()
	{
		log.log(Level.INFO, ++counter + "\tServlet start");
	}
	
	void logMethodName()
	{
		log.log(Level.INFO, Thread.currentThread().getStackTrace()[2].getMethodName());
	}
	
	@Override
	protected void doTrace(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException
	{
		super.doTrace(arg0, arg1);
		logMethodName();
	}
	
	@Override
	public void log(String msg)
	{
		super.log(msg);
		logMethodName();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		super.doGet(req, resp);
		logMethodName();
	}
	
	protected void doUrlParam(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		logMethodName();
		String urlParam = req.getParameter("url");
		if (urlParam != null)
			try
			{
				if (!urlParam.startsWith("http://"))
					urlParam = "http://" + urlParam;
				log.log(Level.INFO, "url=" + urlParam);
				URL url = new URL(urlParam);
				BufferedInputStream in = new BufferedInputStream(url.openStream());
				BufferedOutputStream respOut = new BufferedOutputStream(resp.getOutputStream());
				int Char;
				while ((Char = in.read()) > -1)
				{
					respOut.write(Char);
				}
				in.close();
				
			}
			catch (MalformedURLException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
	}
	
	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException
	{
		try
		{
			super.service(arg0, arg1);
		}
		finally
		{
			logMethodName();
			log.log(Level.INFO, "ContextPath: " + arg0.getContextPath() + "\nServletContext: " + getServletContext());
			log.log(Level.INFO, "URI: " + arg0.getRequestURI());
			log.log(Level.INFO, "Method: " + arg0.getMethod());
			log.log(Level.INFO, "Query: " + arg0.getQueryString());
		}
		
		// if(arg0.getParameter("url") != null)
		// doUrlParam(arg0, arg1);
		// else if(arg0.getMethod().equalsIgnoreCase("GET"))
		// doGet(arg0, arg1);
		// else if(arg0.getMethod().equalsIgnoreCase("POST"))
		// doPost(arg0, arg1);
		// else if(arg0.getMethod().equalsIgnoreCase("HEAD"))
		// doHead(arg0, arg1);
		// else
		//arg1.getWriter().write(arg0.getMethod()+" method not supported yet :)");
	}
	
	@Override
	protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		super.doHead(req, resp);
		logMethodName();
	}
	
	public String greetServer(String input)
	{
		logMethodName();
		String ret = "";
		if (input != null)
			try
			{
				if (!input.startsWith("http://"))
					input = "http://" + input;
				log.log(Level.INFO, "url=" + input);
				URL url = new URL(input);
				URLConnection conn = url.openConnection();
				ByteArrayOutputStream byteArrayBuffer = new ByteArrayOutputStream();
				BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
				byte[] buffer = new byte[2048];
				int lengh = 0;
				while ((lengh = in.read(buffer)) > 0)
				{
					byteArrayBuffer.write(buffer, 0, lengh);
					Arrays.fill(buffer, (byte)0);
				}
				String substr = "content=\"text/html; charset=";  //"<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />";
				String searchArea = byteArrayBuffer.toString();
				int charsetIndex = searchArea.indexOf(substr) + substr.length();
				
				String charset = "utf-8";
				if(charsetIndex > 0)
				{
					int endSharsetIndex = searchArea.indexOf("\"", charsetIndex);
					charset = searchArea.substring(charsetIndex, endSharsetIndex);
				}
				log.log(Level.INFO, "charset:" + charset);
				ret = new String(byteArrayBuffer.toString(charset.toUpperCase()));
				log.log(Level.INFO, ret);
				
			}
			catch (MalformedURLException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		
		return ret;
		
		// String serverIDvletContext().getServerInfo();
		// String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		// return "Hello, " + input + "!<br><br>I am running " + serverInfo +
		// ".<br><br>It looks like you are using:<br>"
		// + userAgent;
	}
	
}
